// pages/join/index.js
const util = require("./../../utils/util.js");
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 表单数据
        storeName: '',
        storeAddress: '',
        contactName: '',
        contactPhone: '',
        idCardFront: '',
        idCardBack: '',
        storePhotos: [],
        images: ["https://xxg.xjdio.com/images/Zxrh/shop/202511/2025110701111565f6c2a4-1a4a-4d51-8dc3-6fa7ea791cfa.png", "https://xxg.xjdio.com/images/Zxrh/shop/202511/2025110701111565f6c2a4-1a4a-4d51-8dc3-6fa7ea791cfa.png"],
        isFormValid: false,
        // 地图相关数据
        showMapModal: false,
        QRimage: '',
        latitude: 39.90469,
        longitude: 116.40717,
        markers: [{
            id: 1,
            latitude: 39.90469,
            longitude: 116.40717,
            title: '选择的位置'
        }]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    // 返回上一页
    goBack: function () {
        wx.navigateBack();
    },

    // 输入框事件处理
    onStoreNameInput: function (e) {
        this.setData({
            storeName: e.detail.value
        });
        this.validateForm();
    },

    onContactNameInput: function (e) {
        this.setData({
            contactName: e.detail.value
        });
        this.validateForm();
    },

    onContactPhoneInput: function (e) {
        this.setData({
            contactPhone: e.detail.value
        });
        this.validateForm();
    },

    // 打开地图选择
    openMapModal: function () {
        this.setData({
            showMapModal: true
        });

        // 初始化地图位置
        this.initMap();
    },

    // 初始化地图
    initMap: function () {
        // 在实际应用中，这里会获取用户当前位置
        wx.getLocation({
            type: 'gcj02',
            success: (res) => {
                this.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                    markers: [{
                        id: 1,
                        latitude: res.latitude,
                        longitude: res.longitude,
                        title: '选择的位置'
                    }]
                });
            }
        });
    },

    // 地图区域变化
    onRegionChange: function (e) {
        if (e.type === 'end') {
            console.log("获取变化")
            // 获取中心点坐标
            const mapCtx = wx.createMapContext('map');
            mapCtx.getCenterLocation({
                success: (res) => {
                    this.setData({
                        latitude: res.latitude,
                        longitude: res.longitude,
                        markers: [{
                            id: 1,
                            latitude: res.latitude,
                            longitude: res.longitude,
                            title: '选择的位置'
                        }]
                    });
                }
            });
        }
    },

    // 确认位置选择
    confirmLocation: function () {
        const that = this;
        console.log("获取地址名称")
        // 根据坐标获取地址信息
        wx.request({
            url: 'https://restapi.amap.com/v3/geocode/regeo',
            data: {
                key: '您的高德地图Key',
                location: `${this.data.longitude},${this.data.latitude}`,
                output: 'json'
            },
            success: (res) => {
                if (res.data.status === '1') {
                    const address = res.data.regeocode.formatted_address;
                    that.setData({
                        storeAddress: address,
                        showMapModal: false
                    });
                    that.validateForm();
                } else {
                    wx.showToast({
                        title: '获取地址失败',
                        icon: 'none'
                    });
                }
            }
        });
    },
    address() {
        let _this = this;
        console.log('address')
        // 首先检查是否支持该API
        if (wx.chooseLocation) {
            wx.chooseLocation({
                success: (res) => {
                    console.log('选择的位置：', res)
                    _this.setData({
                        storeAddress: res.address + res.name,
                        latitude: res.latitude,
                        longitude: res.longitude,
                    });
                    // res 包含 name, address, latitude, longitude
                },
                fail: (err) => {
                    console.error('选择位置失败：', err)
                }
            })
        } else {
            console.error('当前微信版本不支持 chooseLocation API')
        }
        // wx.chooseLocation({
        //     success(res) {
        //         _this.setData({
        //             storeAddress: res.address + res.name,
        //             latitude: res.latitude,
        //             longitude: res.longitude,
        //         });
        //     },
        //     fail(res) {
        //         console.log(res);
        //     }
        // });
    },
    // 关闭地图模态框
    closeMapModal: function () {
        this.setData({
            showMapModal: false
        });
    },

    // 上传身份证正面
    uploadIdCardFront: function () {
        this.chooseImage(1).then(res => {
            this.setData({
                idCardFront: res.tempFilePaths[0]
            });
            this.validateForm();
        });
    },

    // 上传身份证反面
    uploadIdCardBack: function () {
        this.chooseImage(1).then(res => {
            this.setData({
                idCardBack: res.tempFilePaths[0]
            });
            this.validateForm();
        });
    },

    // 上传门面照片
    // uploadStorePhotos: function () {
    //     const remaining = 5 - this.data.storePhotos.length;
    //     if (remaining <= 0) {
    //         wx.showToast({
    //             title: '最多上传5张照片',
    //             icon: 'none'
    //         });
    //         return;
    //     }

    //     this.chooseImage(remaining).then(res => {
    //         const newPhotos = [...this.data.storePhotos, ...res.tempFilePaths].slice(0, 5);
    //         this.setData({
    //             storePhotos: newPhotos
    //         });
    //         this.validateForm();
    //     });
    // },
    uploadStorePhotos(e) {
        // console.log(e.currentTarget.dataset.id);
        const _this = this;
        wx.chooseMedia({
            count: 1,
            mediaType: ['image', 'video'],
            sizeType: ["compressed"],//"original",
            sourceType: ["album", "camera"],
            maxDuration: 180,
            success(res) {
                let dt1 = new Date();
                let dt2 = util.formatTime6(dt1);
                let params = {
                    tablename: "shop",
                    tableid: dt2,
                };
                wx.uploadFile({
                    url: wx._baseUrl + "/ApiAppService/Xncf.Xxgmall_ApiAppService.UploadMedia",
                    filePath: res.tempFiles[0].tempFilePath,
                    header: {
                        "content-type": "multipart/form-data",
                        accept: "application/json",
                    },
                    method: "POST",
                    imgType: 1,
                    name: "Zxrh", //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
                    formData: params, //HTTP 请求中其他额外的 form data
                    success: function (res) {
                        if (res.statusCode == 200) {
                            let datatemp = JSON.parse(res.data);
                            let arr = datatemp.data;//.split(","); //分割数组

                            // if (e.currentTarget.dataset.id == 2) 
                            {
                                // if (e.currentTarget.dataset.index >= 0) {
                                //     _this.data.storePhotos[e.currentTarget.dataset.index] = arr;
                                // } else 
                                {
                                    _this.data.storePhotos.push(arr)
                                }
                                _this.setData({
                                    storePhotos: _this.data.storePhotos
                                })
                            }
                            // else if (e.currentTarget.dataset.id == 1) {
                            //     _this.setData({
                            //         mainImage: arr
                            //     })
                            // }

                        } else {
                            console.log(res)
                            wx.showToast({
                                title: "上传有误",
                            });
                        }
                    },
                    fail: (err) => {
                        wx.showToast({
                            title: "上传失败!",
                        });
                    },
                });
            },
        });
    },
    // 选择图片通用方法
    // chooseImage: function (count) {
    //     return new Promise((resolve, reject) => {
    //         wx.chooseImage({
    //             count: count,
    //             sizeType: ['compressed'],
    //             sourceType: ['album', 'camera'],
    //             success: resolve,
    //             fail: reject
    //         });
    //     });
    // },

    // 移除身份证正面
    removeIdCardFront: function () {
        this.setData({
            idCardFront: ''
        });
        this.validateForm();
    },

    // 移除身份证反面
    removeIdCardBack: function () {
        this.setData({
            idCardBack: ''
        });
        this.validateForm();
    },
    Deletefile(param1) {
        return wx.Http.post("/ApiAppService/Xncf.Xxgmall_ApiAppService.Deletefile", {
            DeletePic: param1,

        });
    },
    // 移除门面照片
    // removeStorePhoto: function (e) {
    //     const index = e.currentTarget.dataset.index;
    //     const storePhotos = this.data.storePhotos;
    //     const myimage=this.data.storePhotos[index];

    //     storePhotos.splice(index, 1);
    //     this.setData({
    //         storePhotos: storePhotos
    //     });
    //     this.validateForm();
    // },
    // 删除轮播图
    removeStorePhoto(e) {
        const _this = this;
        const index = e.currentTarget.dataset.index;
        var contactstemp = this.data.storePhotos;
        var item = contactstemp[index];
        wx.showModal({
            title: '提示',
            content: '是否确认删除',
            complete: (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {

                    _this.Deletefile(item).then((res) => {
                        if (res.data) {
                            contactstemp.splice(index, 1);
                            _this.setData({ storePhotos: contactstemp });
                            _this.validateForm();
                        }
                    })
                }
            }
        })


    },
    // 表单验证
    validateForm: function () {
        const {
            storeName,
            storeAddress,
            contactName,
            contactPhone,
            // idCardFront,
            // idCardBack,
            storePhotos
        } = this.data;

        const isStoreNameValid = storeName.trim().length > 0;
        const isStoreAddressValid = storeAddress.length > 0;
        const isContactNameValid = contactName.trim().length > 0;
        const isContactPhoneValid = /^1[3-9]\d{9}$/.test(contactPhone);
        // const isIdCardFrontValid = idCardFront.length > 0;
        // const isIdCardBackValid = idCardBack.length > 0;&&
        // isIdCardFrontValid && isIdCardBackValid
        const isStorePhotosValid = storePhotos.length > 0;

        const isValid = isStoreNameValid && isStoreAddressValid &&
            isContactNameValid && isContactPhoneValid &&
            isStorePhotosValid;

        this.setData({
            isFormValid: isValid
        });
    },
    // 删除图片
    removePhoto(e) {
        const _this = this;
        // const index = e.currentTarget.dataset.index;
        var contactstemp = this.data.mainImage;
        // var item=contactstemp[index];
        wx.showModal({
            title: '提示',
            content: '是否确认删除',
            complete: (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {

                    _this.Deletefile(contactstemp).then((res) => {
                        if (res.data) {
                            // contactstemp.splice(index, 1);
                            this.setData({ mainImage: '' });

                        }
                    })
                }
            }
        })

    },

    CreateOrUpdateShopAddressAsync(param) {
        return wx.Http.post("/ShopAddressAppService/Xncf.Xxgmall_ShopAddressAppService.CreateOrUpdateShopAddressAsync",
            param
        )
    },
    // 提交表单
    submitForm: function () {
        const _this = this;
        if (!_this.data.isFormValid) {
            wx.showToast({
                title: '请填写完整信息',
                icon: 'none'
            });
            return;
        }
        const param = {
            shopName: _this.data.storeName,
            ShopImageUrl: _this.data.storePhotos.toString(),
            Address: _this.data.storeAddress,
            ContactPhone: _this.data.contactPhone,
            latitude: _this.data.latitude,
            longitude: _this.data.longitude,
            IsActive: true
        }
        wx.showLoading({
            title: '提交中...',
        });
        _this.CreateOrUpdateShopAddressAsync(param).then((res => {
            if (res.data) {
                var myobj = res.data;
                let myid = res.data.id;
                wx.Http.post('/ApiAppService/Xncf.Xxgmall_ApiAppService.GetQrCode', {
                    HRid: myid.toString(),
                    codeType: "shop"
                    // Page:"pages/index/index"
                }).then((res) => {

                    if (res.data) {
                        const param = {
                            Id:myobj.id,
                            ShopQrCodeUrl:res.data,
                            ShopId:myobj.shopId,
                            ShopName:myobj.shopName,
                            ShopImageUrl:myobj.shopImageUrl,
                            ShopDescription:myobj.shopDescription,
                            Address:myobj.address,
                            ContactPhone:myobj.contactPhone,
                            BusinessHours:myobj.businessHours,
                            Latitude:myobj.latitude,
                            Longitude:myobj.longitude,
                            IsActive:myobj.isActive,
                        }
                        _this.CreateOrUpdateShopAddressAsync(param).then((res) => {
                            if (res.data) {
                                wx.navigateBack();
                            }

                        })

                    }

                })
            }
        }))
        // 在实际应用中，这里会调用wx.uploadFile上传图片，然后提交表单数据
        // setTimeout(() => {
        //     wx.hideLoading();
        //     wx.showModal({
        //         title: '提交成功',
        //         content: '我们将在1-3个工作日内审核您的申请，请保持电话畅通。',
        //         showCancel: false,
        //         success: () => {
        //             let _this = this
        //             wx.Http.post('/HRdepartmentAppService/GetQrCode', {
        //                 HRid: id,
        //                 codeType: "shop",
        //             }).then((res) => {
        //                 if (res.data)
        //                     wx.navigateBack();
        //             })

        //         }
        //     });
        // }, 2000);
    }
})